package com.zllkj.mm.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.zllkj.mm.module.UIHelper;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

public abstract class BaseFragment extends Fragment {

    public static int PULL_DOWN = 1;
    public static int LOAD_MORE = 2;

    //输入法管理器
    private InputMethodManager mIMM;

    protected BaseActivity mActivity;
    private Unbinder unbinder;


    public static String ACTION_FRAGMENT_UPDATE = "ACTION_FRAGMENT_UPDATE";

    //获取宿主Activity
    BaseActivity getHoldingActivity() {
        return mActivity;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //宿主Activity验证赋值
        if (context instanceof BaseActivity) {
            this.mActivity = (BaseActivity) context;
            mActivity.registerReceiver(dataUpdateBR,new IntentFilter(ACTION_FRAGMENT_UPDATE));
        } else {
            throw new RuntimeException(context.toString() + "must extends BaseActivity!");
        }


    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity.unregisterReceiver(dataUpdateBR);

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle mBundle = getArguments();
        initBundle(mBundle);
    }

    public View mRootView;

    //获取布局
    protected abstract int getLayoutId();

    public void onKeyBoardShow(){

    }

    public void onKeyBoardHide(){

    }


    boolean isOpened = false;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
            onBindViewBefore(mRootView);
            unbinder = ButterKnife.bind(this, mRootView);
            if (savedInstanceState != null) {
                onRestartInstance(savedInstanceState);
            }
            initView(mRootView);
            loadData();
        } else {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }

        final View activityRootView = getActivity().getWindow().getDecorView().findViewById(android.R.id.content);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > 100) { // 99% of the time the height diff will be due to a keyboard.

                    if (isOpened == false) {
                        //Do two things, make the view top visible and the editText smaller
                        onKeyBoardShow();
                    }
                    isOpened = true;
                } else if (isOpened == true) {
                    isOpened = false;
                    onKeyBoardHide();
                }
            }
        });

        return mRootView;
    }

    protected void notifyDataUpdate(Intent intent){

    }

    protected void initBundle(Bundle bundle) {
    }

    protected void initView(View rootView) {
    }

    protected void loadData() {
    }

    protected void onBindViewBefore(View rootView) {
    }

    protected void onRestartInstance(Bundle bundle) {
    }

    //是否需要隐藏软键盘标识
    private boolean mNeedHideSoft = true;

    @Override
    public void onPause() {
        super.onPause();
        //需要时隐藏软键盘
        if (mNeedHideSoft) {
            hideSoftInput();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //rx取消订阅
        unSubscribe();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(unbinder != null)
            unbinder.unbind();
    }

    /**
     * 显示软键盘
     */
    public void showSoftInput(final View view) {
        if (view == null) return;
        initImm();
        view.requestFocus();//请求焦点
        mNeedHideSoft = true;//隐藏键盘标志true,为onPause时隐藏软键盘
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                mIMM.showSoftInput(view, InputMethodManager.SHOW_FORCED);
            }
        }, 200);
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftInput() {
        if (getView() != null) {
            initImm();
            mIMM.hideSoftInputFromWindow(getView().getWindowToken(), 0);
        }
    }

    private void initImm() {
        if (mIMM == null) {
            mIMM = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        }
    }

    // rx总线
    private CompositeSubscription compositeSubscription = new CompositeSubscription();

    //rx总线里添加订阅
    public void addSubscribe(Subscription subscription) {
        if(compositeSubscription == null)
            compositeSubscription = new CompositeSubscription();
        compositeSubscription.add(subscription);
    }

    //rx取消订阅
    public void unSubscribe() {
        if (compositeSubscription != null) {
            compositeSubscription.unsubscribe();
            compositeSubscription = null;
        }
    }

    protected void addFragment(BaseFragment fragment) {
        if (/*MainActivity.mainActivityResume*/true) {
            UIHelper.showPage(fragment);
            return;
        }
        if (null != fragment && getHoldingActivity() instanceof BaseCommonActivity) {
            ((BaseCommonActivity) getHoldingActivity()).addFragment(fragment);
        }
    }

    //移除fragment
    protected void removeFragment() {
        if (getHoldingActivity() instanceof BaseCommonActivity) {
            ((BaseCommonActivity) getHoldingActivity()).removeFragment();
        }
    }

    BroadcastReceiver dataUpdateBR = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            notifyDataUpdate(intent);
        }
    };
}
